package recallin.activities;

import org.mapsforge.android.maps.overlay.ItemizedOverlay;
import org.mapsforge.android.maps.overlay.OverlayItem;
import org.mapsforge.core.GeoPoint;

import recallin.database.DatabaseUtility;
import recallin.database.Place;
import recallin.gui.PlacesAdapter;
import recallin.navigation.FindPath;
import recallin.social.facebook.Places;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

/**
 * This handles all favorites and POI's.
 * @author philipmasek
 *
 */

public class PlacesActivity extends Activity {

	private Handler mHandler;
	private PlacesAdapter adapter;
	private ListView listView;
	private static String currentCategory = "Favorites";
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.placesmenu);

		EditText searchField = (EditText) findViewById(R.id.places_search_field);
		MenuActivity.setupSearchField(this, searchField);

		listView = (ListView) findViewById(R.id.places_list_view);
		listView.setEmptyView(findViewById(R.id.empty_view1));
		Spinner spinner = (Spinner) findViewById(R.id.places_spinner);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				System.gc();
				if (!getDatabaseName(pos).equals("Favorites")) {
					refreshDB(filterByCat(pos));
					setCurrentCategory(getDatabaseName(pos));
				} else
					refreshDB(null);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		mHandler = new Handler();

		listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listView.requestFocus();
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		listView.setTextFilterEnabled(true);

		Thread thread = new Thread() {
			@Override
			public void run() {
				Looper.prepare();
//				System.out.println(MenuActivity.connection.syncFavorites());
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						refreshDB(null);
					}
				});
				super.run();
			}
		};
		thread.start();
		
		
		searchField.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				System.gc();
				((PlacesAdapter) listView.getAdapter()).getFilter().filter(s);
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> tmp, View v, int pos1,
					long pos2) {
				System.gc();
				adapter.getCursor().moveToPosition(pos1);
				if (adapter.getCursor().getString(11) == null) {
					DatabaseUtility.getDatabase().execSQL(
							"UPDATE places SET favorite_name='"
									+ adapter.getCursor().getString(10)
									+ "', status=" + Place.NEW
									+ "  WHERE latitude="
									+ adapter.getCursor().getDouble(9)
									+ " AND longitude="
									+ adapter.getCursor().getDouble(8) + "");
				} else
					DatabaseUtility.getDatabase().execSQL(
							"UPDATE places SET favorite_name=null, status="
									+ Place.DELETED + " WHERE latitude="
									+ adapter.getCursor().getDouble(9)
									+ " AND longitude="
									+ adapter.getCursor().getDouble(8) + "");

				adapter.getCursor().requery();
				adapter.notifyDataSetChanged();
			}
		});

		listView.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {

				return false;
			}
		});

		registerForContextMenu(listView);

	}

	public Cursor filter(CharSequence constraint, int size,
			boolean onlyFavorites) {
		if (onlyFavorites) {
			return DatabaseUtility
					.getDatabase()
					.rawQuery(
							"SELECT * FROM places WHERE favorite_name IS NOT null ORDER BY favorite_name", null);
		} else if (constraint == null || constraint.length() == 0) {
			// Return the full list of countries
			return DatabaseUtility.getDatabase().rawQuery(
					"SELECT * FROM places ORDER BY favorite_name DESC LIMIT "
							+ size, null);
		} else {
			return DatabaseUtility.getDatabase().rawQuery(
					"SELECT * FROM PLACES where (favorite_name like '"
							+ constraint
							+ "%') or (favorite_name is null and name like '"
							+ constraint
							+ "%') ORDER BY favorite_name DESC LIMIT " + size,
					null);
		}
	}

	public Cursor filterByCat(int categoryIndex) {
		System.gc();
		System.out.println("SELECT * FROM places WHERE category='"
				+ getDatabaseName(categoryIndex)
				+ "' ORDER BY favorite_name DESC LIMIT ");
		if (categoryIndex == 0) {
			
			return DatabaseUtility.getDatabase().rawQuery(
					"SELECT * FROM places WHERE favorite_name is not null order by favorite_name, null",null);
		}else if (MainActivity.getCurrentLocation() != null) {

			Location l = MainActivity.getCurrentLocation();

			return DatabaseUtility.getDatabase().rawQuery(
					"SELECT * FROM places WHERE category='"
							+ getDatabaseName(categoryIndex)
							+ "' order by ((latitude-" + l.getLatitude()
							+ ")* (latitude-" + l.getLatitude()
							+ ")+ (longitude-" + l.getLongitude()
							+ ")* (longitude-" + l.getLongitude() + ")) LIMIT "
							+ 50, null);
		} else
			return DatabaseUtility.getDatabase()
					.rawQuery(
							"SELECT * FROM places WHERE category='"
									+ getDatabaseName(categoryIndex)
									+ "' order by favorite_name DESC LIMIT "
									+ 50, null);
	}

	public static String getDatabaseName(int index) {
		switch (index) {
		case 1:
			return "Automotive";
		case 2:
			return "Eating_Drinking";
		case 3:
			return "Government_and_Public_Services";
		case 4:
			return "Health_care";
		case 5:
			return "Leisure";
		case 6:
			return "Lodging";
		case 7:
			return "Night_Life_and_Business";
		case 8:
			return "Sports";
		case 9:
			return "Tourism";
		default:
			return "Favorites";
		}
	}

	public void refreshDB(final Cursor c) {
		Thread thread = new Thread() {

			@Override
			public void run() {
				Looper.prepare();
//				dialog = ProgressDialog.show(PlacesActivity.this, "",
//						"Loading information");
				System.gc();
				if (c == null) {
					adapter = new PlacesAdapter(PlacesActivity.this, filter("",
							10, true));
				} else
					adapter = new PlacesAdapter(PlacesActivity.this, c);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						listView.setAdapter(adapter);
//						dialog.dismiss();
					}
				});
			}
		};
		thread.start();
	}

	public static String getCurrentCategory() {
		return currentCategory;
	}

	public void setCurrentCategory(String currentCategory) {
		this.currentCategory = currentCategory;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.places_list_view
				&& adapter.getCursor().getString(11) != ""
				|| adapter.getCursor().getString(11) != null) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			((PlacesAdapter) listView.getAdapter()).getCursor().moveToPosition(
					info.position);
			menu.setHeaderTitle(((PlacesAdapter) listView.getAdapter())
					.getCursor().getString(11));
			String[] menuItems = { "Take me here", "Rename" };
			for (int i = 0; i < menuItems.length; i++) {
				menu.add(0, i, i, menuItems[i]);
			}
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		String[] menuItems = { "Take me here", "Rename" };
		String menuItemName = menuItems[menuItemIndex];
		final Cursor c = ((PlacesAdapter) listView.getAdapter()).getCursor();

		if (menuItemName.equals("Rename")) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					PlacesActivity.this).create();
			alertDialog.setTitle("Rename");
			final EditText rename = new EditText(this.getApplicationContext());
			rename.setText(c.getString(11));
			rename.requestFocus();
			rename.setGravity(Gravity.TOP);
			rename.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT));
			rename.setLines(1);
			alertDialog.setView(rename);
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					DatabaseUtility.getDatabase().execSQL(
							"UPDATE places SET favorite_name='"
									+ rename.getText() + "', status="
									+ Place.NEW + " WHERE latitude="
									+ c.getDouble(9) + " AND longitude="
									+ c.getDouble(8) + "");
					c.requery();
					adapter.notifyDataSetChanged();
				}
			});
			alertDialog.setButton2("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// here you can add functions
						}
					});
			alertDialog.show();
		}else if(menuItemName.equals("Take me here")){
			Location location = new Location(LocationManager.GPS_PROVIDER);
			MainActivity.setMode(MainActivity.PEDESTRIAN_MODE);
			location.setLatitude(Places.TIMES_SQUARE_LAT);
			location.setLongitude(Places.TIMES_SQUARE_LON);
			OverlayItem overlayItem = new OverlayItem(new GeoPoint(c.getDouble(8), c.getDouble(9)), c.getString(c
					.getColumnIndex("favorite_name")), "");
			overlayItem.setMarker(ItemizedOverlay.boundCenterBottom(getResources().getDrawable(R.drawable.pin_poi)));
			MainActivity.setDestinationPoint(new GeoPoint(c.getDouble(8), c.getDouble(9)));
			MainActivity.addOverlayItem(overlayItem);
			MainActivity.startingRoute = true;
			finish();
		}

		return true;
	}

}
